<?php

define('COMMON_FUNC_PATH', APP_PATH . '/Common/Common/functions');

require_once(APP_PATH . '/Common/Common/plugin.php'); //加载插件相关公共函数库
require_once(APP_PATH . '/Common/Common/developer.php'); //加载二次开发公共函数库


// 为了更加清晰，将功能函数分文件存放
require_once(COMMON_FUNC_PATH . '/file.php');
require_once(COMMON_FUNC_PATH . '/email.php');
require_once(COMMON_FUNC_PATH . '/url.php');

use Helper\Controller\UploadController;
use Admin\Controller\SettingController;
use Common\Lib\Think\Page;

/**
 * 返回带协议的域名
 */
function x_get_host(){
    $host=$_SERVER["HTTP_HOST"];
    $protocol=is_ssl()?"https://":"http://";
    return $protocol.$host;
}

/**
 * 获取IP返回地址的函数
 *
 * @param string $string
 * @return string
 */
function x_convert_ip_to_area($ip) {
    static $ipLocation = null;
    if (empty($ipLocation)) {
        // 实例化类 参数表示IP地址库文件
        $ipLocation = new \Org\Net\IpLocation('UTFWry.dat');
    }
    // 获取某个IP地址所在的位置
    $arr = $ipLocation->getlocation($ip);
    return $arr['country'] . $arr['area'];
}

/**
 * 判断输入的字符串是否是一个合法的手机号(仅限中国大陆)
 *
 * @param string $string
 * @return boolean
 */
function x_isMobile($string) {
    if (preg_match('/^[1]+[3,4,5,7,8]+\d{9}$/', $string))
        return true;
    return false;
}

/**
 * 判断输入的字符串是否是一个合法的手机号(仅限中国大陆)
 *
 * @param string $string
 * @return boolean
 */
function x_isImage($fileName) {
    $ext = explode('.', $fileName);
    $ext_seg_num = count($ext);
    if ($ext_seg_num <= 1)
        return false;

    $ext = strtolower($ext[$ext_seg_num - 1]);
    $nort = in_array($ext, array('jpeg', 'jpg', 'png', 'gif'));
    $hext = explode('?', $ext);
    $httt = in_array($hext[0], array('jpeg', 'jpg', 'png', 'gif'));
    if($nort || $httt){
        return true;
    }else{
        return false;
    }
}

/**
 * 过滤不安全的HTML代码
 */
function x_securityEditorHtml($str) {
    $farr = array(
        "/\s+/", //过滤多余的空白
        "/<(\/?)(script|i?frame|style|html|body|title|link|meta|\?|\%)([^>]*?)>/isU",
        "/(<[^>]*)on[a-zA-Z]+\s*=([^>]*>)/isU"
    );
    $tarr = array(
        " ",
        "＜\\1\\2\\3＞",
        "\\1\\2",
    );
    $str = preg_replace($farr, $tarr, $str);
    return $str;
}

function x_get_tree($arr = array(), $id, $pid, $name, $myid = 0) {
    $tree = new \Common\Lib\Util\Tree();
    $tree->icon = array('&nbsp;&nbsp;&nbsp;│&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;├─&nbsp;&nbsp;', '&nbsp;&nbsp;&nbsp;└─&nbsp;&nbsp;');
    $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
    $tree->tree($arr, $id, $pid, $name);
    return $tree->getArray($myid);
}

/**
 * 获取当前登录的管事员id
 * @return int
 */
function x_get_admin_id() {
    return session('admin.admin_id');
}

/**
 * 判断是否是超级管理员
 * @return int
 */
function x_is_administrator() {
    return session('admin.role_ids') === \Common\Model\AdminModel::DEFAULT_ADMIN_ROLE;
}

/**
 * 判断前台用户是否登录
 * @return boolean
 */
function x_is_user_login(){
    $user = session('user');
    return !empty($user);
}

/**
 * 获取当前登录的前台id
 * @return int
 */
function x_get_user_id() {
    return session('user.user_id');
}

/**
 * 检查权限
 * @param uid  int           认证用户的id
 * @param name string|array  需要验证的规则列表,支持逗号分隔的权限规则或索引数组
 * @param relation string    如果为 'or' 表示满足任一条规则即通过验证;如果为 'and'则表示需满足所有规则才能通过验证
 * @return boolean           通过验证返回true;失败返回false
 */
function x_check_rule($uid,$name=null,$relation='or'){

    if(empty($uid)){
        return false;
    }
    $xAuth =new \Common\Lib\Think\XAuth();
    if(empty($name)){
        $name=strtolower(MODULE_NAME."/".CONTROLLER_NAME."/".ACTION_NAME);
    }

    return $xAuth->check($uid, $name, $relation);
}

/**
 * 根据广告名称获取广告内容
 * @param string $ad
 * @return 广告内容
 */

function x_get_ad($ad) {
    $ad_model = M("Ad");
    $ad = $ad_model->field("ad_content")->where("ad_name='$ad' and status=1")->find();
    return htmlspecialchars_decode($ad['ad_content']);
}

/*
 * 更新系统配置文件
 * @param array $data <br>如：array("URL_MODEL"=>0);
 * @return boolean
 * */
function x_set_sys_config($data) {
    if (!is_array($data) || empty($data)) {
        return false;
    }

    $configs = array();
    $config_file = X_DATA_PATH . 'conf/config.php';
    if (file_exists($config_file)) {
        $configs = include $config_file;
    }
    $configs = array_merge($configs, $data);
    $result = file_put_contents($config_file, "<?php\r\n\treturn " . var_export($configs, true) . ";");
    file_exists($file = RUNTIME_PATH . 'common~runtime.php') && @unlink($file);
    return $result;
}

function x_get_config_by_key($key) {
    return  D('Common/Setting')->getSettingByKey($key);
}


/**
 * 转化数据库保存图片的文件路径，为可以访问的url
 * @param string $file
 * @param mixed $style  样式(七牛)
 * @return string
 */
function x_get_image_url($file, $style = '') {

    if (strpos($file, "http") === 0 || strpos($file, 'https') === 0 || strpos($file, "/") === 0) {
        return $file;
    } else {
        $filepath = C("TMPL_PARSE_STRING.__UPLOAD__") . $file;
        if (C('FILE_UPLOAD_TYPE') == UploadController::STORAGE_LOCAL) {
            if (strpos($filepath, 'http') !== 0 || strpos($file, 'https') === 0) {
                $filepath = x_get_host() . $filepath;
            }
        }

        if (C('FILE_UPLOAD_TYPE') == UploadController::STORAGE_QINIU) {
            $storage_setting = x_get_config_by_key(SettingController::STORAGE_KEY);
            $qiniu_setting   = $storage_setting['Qiniu']['setting'];
            $filepath = $qiniu_setting['protocol'] . '://' .
                $storage_setting['Qiniu']['domain'] . "/" . $file . $style;
        }
        return $filepath;
    }
}

//获取时间格式
function x_get_date() {
    return date('Y-m-d H:i:s');
}

/**
 * 所有用到密码的不可逆加密方式
 *
 * @param string $password
 * @param string $authcode
 * @return string
 */
function x_encrypt_password($password, $authcode = '')
{
    $authcode = empty($authcode) ? C('AUTHCODE') : $authcode;
    return md5(md5($password) . md5($authcode));
}

/**
 * 内容分页
 * @param string $content 内容
 * @param string
 * @return array 返回符合条件的页面
 */
function x_content_page($content){
    $contents  = explode('_ueditor_page_break_tag_',$content);
    $totalsize = count($contents);
    $pagesize  = 1;
    $page = new Page($totalsize, $pagesize);
    $data['content']= $contents[$page->firstRow];
    $data['page']   = $page->show();
    return $data;
}

/**
 * 获取项目应用当前模板下的模板列表
 * @return array
 */
function x_get_tpl_file_list($template_path) {
    $dirinfo = \Common\Lib\Util\File::get_dirs($template_path);
    $files = $dirinfo['file'];
    $tpl_files=array();
    foreach ($files as $f){
        if($f!="." || $f!=".."){
            if(is_file($template_path.$f)){
                $suffix=C("TMPL_TEMPLATE_SUFFIX");
                $result=preg_match("/$suffix$/", $f);
                if($result){
                    $tpl=str_replace($suffix, "", $f);
                    $tpl_files[$tpl]=$tpl;
                }else if(preg_match("/\.php$/", $f)){
                    $tpl=str_replace($suffix, "", $f);
                    $tpl_files[$tpl]=$tpl;
                }
            }
        }
    }
    return $tpl_files;
}

function x_admin_get_tpl_file_list() {
    $template_path = C("X_TMPL_PATH").C("X_DEFAULT_THEME")."/PcHome/";
    return x_get_tpl_file_list($template_path);
}

/**
 * 获取目录中目录名
 * @param string $pattern 检索模式 搜索模式 *.txt,*.doc; (同glog方法)
 * @param int $flags
 */
function x_scan_dir($pattern,$flags=null){
    $files = array_map('basename',glob($pattern, $flags));
    return $files;
}




/**
 *
 * @param unknown_type $navcatname
 * @param unknown_type $datas
 * @param unknown_type $navrule
 * @return string
 */
function x_get_all_nav_list($navcatname,$datas,$navrule){
    $nav = array();
    $nav['name']=$navcatname;
    $nav['urlrule']=$navrule;
    $nav['items']=array();

    foreach($datas as $t){
        $urlrule=array();
        $action=$navrule['action'];
        $urlrule['action']=$action;
        $urlrule['param']=array();
        if(isset($navrule['param'])){
            foreach ($navrule['param'] as $key=>$val){
                $urlrule['param'][$key]=$t[$val];
            }
        }

        $nav['items'][] = array(
            "label" => $t[$navrule['label']],
            "url" => U($action, $urlrule['param']),
            "rule" => base64_encode(serialize($urlrule)),
            "parentid" => empty($navrule['parentid']) ? 0 : $t[$navrule['parentid']],
            "id" => $t[$navrule['id']],
        );
    }
    return $nav;
}
